package com.incrediblesoft.redjey.demo;

import com.incrediblesoft.redjey.backgrounds.SimpleBackground;
import com.incrediblesoft.redjey.borders.SimpleBorder;
import com.incrediblesoft.redjey.layouts.GridLayout;
import com.incrediblesoft.redjey.event.ActionEvent;
import com.incrediblesoft.redjey.event.MouseEvent;
import com.incrediblesoft.redjey.event.ActionListener;
import com.incrediblesoft.redjey.event.MouseListener;
import com.incrediblesoft.redjey.CustomImage;
import com.incrediblesoft.redjey.*;
import com.incrediblesoft.redjey.UIManager;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Font;

public class RedJDemo extends MIDlet implements Runnable, ActionListener, MouseListener
{
    private static RedJDemo instance;
    private Display display;
    private RedJDemoCanvas canvas;
    private boolean initialized;

    CustomButton componentsBtn;
    CustomButton windowsBtn;
    CustomButton aboutBtn;
    CustomButton quitBtn;
    Window homeWindow, aboutWindow;
    Button goHomeBtn, closeBtn;

    public RedJDemo()
    {
        super();
        instance = this;
        display = Display.getDisplay(this);
    }

    public static RedJDemo getInstance()
    {
        return instance;
    }

    protected void startApp() throws MIDletStateChangeException
    {
        if (!initialized)
        {
            new Thread(this).start();
        }
        else
        {
            display.setCurrent(RedJDemoCanvas.getInstance());
            canvas.setState(RedJDemoCanvas.INIT_AND_WORK_STATE);
        }
    }

    protected void pauseApp()
    {
        canvas.setState(RedJDemoCanvas.PAUSED_STATE);
    }

    protected void destroyApp(boolean b)
    {
        canvas.setState(RedJDemoCanvas.EXIT_STATE);
    }

    public static void quitApp()
    {
        instance.destroyApp(true);
        instance.notifyDestroyed();
        instance = null;
    }

    public void run()
    {
        try
        {
            //Creating our canvas
            canvas = new RedJDemoCanvas();
            //Set unbelievable framerate :)
            canvas.setFps(30);
            display.setCurrent(canvas);

            //Init out canvas
            canvas.setState(RedJDemoCanvas.INIT_STATE);

            while (canvas.getState() == RedJDemoCanvas.INIT_STATE)
                synchronized (this)
                {
                    wait(50);
                }

            UIManager.setMIDlet(this);
            //Once assigned, UIManager will use dimension info from canvas.
            //So, do not assign not initialized canvas
            UIManager.setCanvas(canvas);
            //Resources listed in styles description file
            //for at the moment must be cached manually
            //You can also cache your own resources
            UIManager.cacheImage("/res_ui.png");
            UIManager.cacheImage("/java.png");
            UIManager.cacheImage("/strip8bit.png");
            UIManager.cacheImage("/gnome.png");
            UIManager.cacheImage("/components.png");
            UIManager.cacheImage("/windows.png");
            UIManager.cacheImage("/exit.png");
            UIManager.cacheImage("/question.png");
            UIManager.cacheImage("/process-working.png");
            UIManager.cacheImage("/about.png");
            UIManager.cacheImage("/icon.png");

            //Load default styles
            UIManager.loadStylesFromResource("/defaults.style", false);


            /****************************************************************************/
            // If you want a custom style but do not wish to put it in resource file,
            // you may do like this
            Label title = new Label("REDJEY DEMO. API v0.0.4");
            Style titleStyle = title.getCurrentStyle();
            titleStyle.setFont(CustomFont.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE, 0xFFFF0000));
            title.setStyle(titleStyle);

            // Create a custom file from default one
            Style notfocusedStyle = UIManager.getStyle("Button", UIManager.DEFAULT_SET, Component.NORMAL).clone();
            Style focusedStyle = UIManager.getStyle("Button", UIManager.DEFAULT_SET, Component.PRESSED).clone();

            // Create custom round border
            SimpleBorder border = new SimpleBorder(1, 0, 10, 10);
            // Assign border
            notfocusedStyle.setBorder(border);
            focusedStyle.setBorder(border);

            // Assign round red background
            // Note: Components without background are transparent.
            focusedStyle.setBackground(new SimpleBackground(0xFFFF0000, 10, 10));

            // Register these styles in UIManager's register under the name 'custom'
            UIManager.registerStyle("Button", "home", Component.NORMAL, notfocusedStyle);
            UIManager.registerStyle("Button", "home", Component.FOCUSED, focusedStyle);
            UIManager.registerStyle("Button", "home", Component.PRESSED, focusedStyle);

            // When creating components, we may specify which style class to use.
            // Here we specify 'custom' one instead of default.
            componentsBtn = new CustomButton("Components", new CustomImage(UIManager.getImage("/components.png")), "home");
            windowsBtn = new CustomButton("Windows", new CustomImage(UIManager.getImage("/windows.png")), "home");
            componentsBtn.addActionListener(this);
            windowsBtn.addActionListener(this);
            quitBtn = new CustomButton("Quit", new CustomImage(UIManager.getImage("/exit.png")), "home");
            quitBtn.addActionListener(this);

            // Create container to hold 2x2 buttons (minimum)
            Container container = new Container();
            Style style = container.getCurrentStyle();
            style.setBorder(new SimpleBorder(1, 0xffcccccc, 10, 10));
            container.setStyle(style);
            container.setLayout(new GridLayout(2, 2));
            container.add(componentsBtn);
            container.add(windowsBtn);

            CustomImage questionImage = new CustomImage(UIManager.getImage("/question.png"));

            for (int i=0; i<2; i++)
            {
                CustomButton b = new CustomButton("Not available",questionImage, "home");
                container.add(b);
            }

            aboutBtn = new CustomButton("About", new CustomImage(UIManager.getImage("/about.png")), "home");
            aboutBtn.addActionListener(this);

            container.add(aboutBtn);
            
            // This button will increase row number in GridLayout by one.
            container.add(quitBtn);

            // Create top-level container (Window)
            homeWindow = new Window();
            // Say to layout manager to center all child elements
            homeWindow.setContentAlignment(Component.HCENTER_ALIGNMENT);
            // Add children
            homeWindow.add(title);
            homeWindow.add(container);
            // Set size to screen size
            homeWindow.setFullScreen();
            //homeWindow.setLocation(UIManager.getCanvas().getWidth() - size.width >> 1, UIManager.getCanvas().getWidth() - size.width >> 1);
            // I want to put container with buttons in the center of window, ingoring layout manager's placement
            container.setLocation(homeWindow.getWidth() - container.getWidth() >> 1, homeWindow.getHeight() - container.getHeight() >> 1);
            // Show on screen
            homeWindow.setVisible(true);
            // Set working state
            canvas.setState(RedJDemoCanvas.WORKING_STATE);

            initialized = true;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            quitApp();
        }
    }

    public void actionPerformed(ActionEvent event)
    {
        Component source = event.getSource();

        if (source == quitBtn)
            quitApp();
        else if (source == componentsBtn)
        {
            homeWindow.setVisible(false);

            ComponentsPage demoPage = new ComponentsPage(homeWindow);
            demoPage.setFullScreen();
            demoPage.setVisible(true);
        }
        else if (source == windowsBtn)
        {
            homeWindow.setVisible(false);
            //UIManager.setBackgroundColor(0xFFFFFFFF);

            Button closeBtn = new Button("x");
            closeBtn.addActionListener(this);

            Style style = new Style(null, null, new SimpleBorder(1, 0), null);
            Style styleA = style.clone();
            styleA.setBackground(new SimpleBackground(0xFFFF0000));

            Window windowA = new Window();
            windowA.add(new Label("Window A"));
            windowA.add(new TextPane("Trails issue in is process."));
            windowA.add(closeBtn);
            windowA.setStyle(styleA);
            windowA.setSize(UIManager.getCanvas().getWidth() / 2, UIManager.getCanvas().getHeight() / 2);
            windowA.setLocation(UIManager.getCanvas().getWidth() / 8, UIManager.getCanvas().getHeight() / 8);
            windowA.addMouseListener(this);
            windowA.setVisible(true);

            closeBtn.setLocation(windowA.getClientSize().width - closeBtn.getWidth(), 0);

            closeBtn = new Button("x");
            closeBtn.addActionListener(this);

            Style styleB = style.clone();
            styleB.setBackground(new SimpleBackground(0xFF00FF00));

            Window windowB = new Window();
            windowB.add(new Label("Window B"));
            windowB.add(new TextPane("Trails issue in is process."));
            windowB.add(closeBtn);
            windowB.setStyle(styleB);
            windowB.setSize(UIManager.getCanvas().getWidth() / 2, UIManager.getCanvas().getHeight() / 2);
            windowB.setLocation(UIManager.getCanvas().getWidth() / 3, UIManager.getCanvas().getHeight() / 3);
            windowB.addMouseListener(this);
            windowB.setVisible(true);

            closeBtn.setLocation(windowB.getClientSize().width - closeBtn.getWidth(), 0);
        }
        else if (source == aboutBtn)
        {
            aboutWindow = new Window();
            aboutWindow.getCurrentStyle().setBorder(new SimpleBorder(2, 0));
            aboutWindow.setContentAlignment(Component.HCENTER_ALIGNMENT);
            aboutWindow.setModal(true);

            aboutWindow.add(new Button(null, UIManager.getCustomImage("/icon.png"), "imageitem"));
            aboutWindow.add(new Label("RedJey GUI demo"));
            aboutWindow.add(new Label("GNU Lesser Public License"));
            aboutWindow.add(new Label("Author: Yevgen Krapiva"));
            aboutWindow.add(new Label("Email: ykrapiva@gmail.com"));
            aboutWindow.add(new Label("http://code.google.com/p/redjey/"));

            closeBtn = new Button("Close");
            closeBtn.addActionListener(this);
            aboutWindow.add(closeBtn);

            aboutWindow.pack();
            aboutWindow.setLocation(UIManager.getCanvas().getWidth() - aboutWindow.getWidth() >> 1, UIManager.getCanvas().getHeight() - aboutWindow.getHeight() >> 1);
            aboutWindow.setVisible(true);
        }
        else if (source == closeBtn)
        {
            aboutWindow.setVisible(false);
            aboutWindow = null;

            homeWindow.setVisible(true);
        }
        else if (source instanceof Button)
        {
            Button button = (Button) source;
            if (button.getText().equals("x"))
            {
                button.getParent().setVisible(false);
                if (UIManager.getNumWindows() == 0)
                    homeWindow.setVisible(true);
            }
        }
    }


    public void mousePressed(MouseEvent event)
    {
        
    }

    public void mouseReleased(MouseEvent event)
    {

    }

    public void mouseClicked(MouseEvent event)
    {
       
    }

    public void mouseScrolled(MouseEvent event)
    {
        int dx = event.getID() == MouseEvent.MOUSE_SCROLL_HORIZONTAL ? event.getValue() : 0;
        int dy = event.getID() == MouseEvent.MOUSE_SCROLL_VERTICAL ? event.getValue() : 0;

        Window window = (Window) event.getSource();
        window.setLocation(window.getX() - dx, window.getY() - dy);
        window.repaint();
    }
}
